package com.ruicar.afs.cloud.afscase.job.loan;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.loanactivatepool.service.LoanActivateService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.LoanWorkflowService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.job.core.biz.model.ReturnT;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJob;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJobHandler;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@AfsJob
@AllArgsConstructor
@Slf4j
@Component
public class LoanActiveJob {

    private final LoanActivateService service;
    private final CaseContractInfoService caseContractInfoService;
    private final LoanWorkflowService loanWorkflowService;
    private final CaseBaseInfoService caseBaseInfoService;
    private ApproveLoanInfoService approveLoanInfoService;

   /**
    * @param
    * @description 合同激活自动任务
    */
    @AfsJobHandler(value = "loanActivateAutoAudit")
    public ReturnT<String> loanActivateAutoAudit(String param) {
        service.loanActivateAutoAudit();
        return ReturnT.SUCCESS;
    }

    /**
     * 自动废弃案件
     */
    @AfsJobHandler(value = "autoDiscardCase")
    public ReturnT<String> autoDiscardCase(String param){
        log.info("启动定时任务【自动废弃案件】");
        try{
            List<CaseBaseInfo> newCarList = caseBaseInfoService.list(Wrappers.<CaseBaseInfo>query().lambda()
                    .le(CaseBaseInfo::getPassLastDate, DateUtil.offsetDay(new Date(),-60))
                    .eq(CaseBaseInfo::getBusinessType, BusinessTypeEnum.NEW_CAR.getCode()));
            if (newCarList.size()!=0){
                log.info("检测到{}单新车放款申请已超审批时效（60天）的案件",newCarList.size());
                newCarList.forEach( newCar -> {
                    CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                            .eq(CaseContractInfo::getApplyNo,newCar.getApplyNo()));
                    if(ObjectUtils.isNotEmpty(caseContractInfo) && StringUtils.isNotBlank(caseContractInfo.getApplyStatus()) && caseContractInfo.getApplyStatus().equals(ApplyStatusEnum.LOAN_RETURN.getState())){
                        //修改合同状态
                        caseContractInfo.setApplyStatus(ApplyStatusEnum.LOAN_DISCARD.getState());
                        caseContractInfo.setContractStatus(ContractStatusEnum.contractCancel);
                        caseContractInfoService.updateById(caseContractInfo);
                        //取消信息通知进件系统
                        approveLoanInfoService.sendListToApplyNotic(newCar.getApplyNo());
                        //结束工作流
                        loanWorkflowService.giveUpWorkflow(caseContractInfo.getContractNo(), LoanProcessTypeEnum.GENERAL_LOAN.getCode());
                    }
                    if(ObjectUtils.isEmpty(caseContractInfo)){
                        newCar.setBusinessStateIn(AfsEnumUtil.key(BusinessStateInEnum.CANCEL));
                        caseBaseInfoService.updateById(newCar);
                        //取消信息通知进件系统
                        approveLoanInfoService.sendListToApplyNotic(newCar.getApplyNo());
                    }
                });
            }
            List<CaseBaseInfo> oldCarList = caseBaseInfoService.list(Wrappers.<CaseBaseInfo>query().lambda()
                    .le(CaseBaseInfo::getPassLastDate, DateUtil.offsetDay(new Date(),-30))
                    .eq(CaseBaseInfo::getBusinessType, BusinessTypeEnum.OLD_CAR.getCode()));
            if (oldCarList.size()!=0){
                log.info("检测到{}单二手车放款申请已超审批时效（30天）的案件",oldCarList.size());
                oldCarList.forEach( oldCar -> {
                    CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                            .eq(CaseContractInfo::getApplyNo, oldCar.getApplyNo()));
                    if (ObjectUtils.isNotEmpty(caseContractInfo) && StringUtils.isNotBlank(caseContractInfo.getApplyStatus()) && caseContractInfo.getApplyStatus().equals(ApplyStatusEnum.LOAN_RETURN.getState())) {
                        //修改合同状态
                        caseContractInfo.setApplyStatus(ApplyStatusEnum.LOAN_DISCARD.getState());
                        caseContractInfo.setContractStatus(ContractStatusEnum.contractCancel);
                        caseContractInfoService.updateById(caseContractInfo);
                        //取消信息通知进件系统
                        approveLoanInfoService.sendListToApplyNotic(oldCar.getApplyNo());
                        //结束工作流
                        loanWorkflowService.giveUpWorkflow(caseContractInfo.getContractNo(), LoanProcessTypeEnum.GENERAL_LOAN.getCode());
                    }
                    if(ObjectUtils.isEmpty(caseContractInfo)){
                        oldCar.setBusinessStateIn(AfsEnumUtil.key(BusinessStateInEnum.CANCEL));
                        caseBaseInfoService.updateById(oldCar);
                        //取消信息通知进件系统
                        approveLoanInfoService.sendListToApplyNotic(oldCar.getApplyNo());
                    }
                });
            }
            log.info("定时任务【自动废弃案件】执行成功");
            return ReturnT.SUCCESS;
        }catch (Exception e){
            log.error("定时任务【自动废弃案件】执行失败",e);
            return ReturnT.FAIL;
        }
    }

}
